package infopreserve.main.mobile;

import java.io.File;
import java.util.ArrayList;

import infopreserve.main.mobile.R;
import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class UploadFile extends Activity  {
	
	private ListView list;
	private UploadListView adapter;
	private ArrayList<Item> uploadList = new ArrayList<Item>();
	private String path ="";
	private String size = "size";
	private String[] category_items = new String[]{
		"exsample item"	
	};
	private Dialog d;
	private TextView t;
	private EditText filename;
	private NotificationManager nm;
	private String ns;
	private static final int HELLO_ID = 1;
	private boolean mRun = false;
	private Notification noti;
	private long fileSize;

	 	@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.upload);
	        ImageButton but = (ImageButton) findViewById(R.id.add);
	    	but.setOnClickListener(new View.OnClickListener() {
	    		@Override
	    		public void onClick(View v) {
	    	    	newUploadItem();
	    		}
	    	});
	    d = new Dialog(this);
	 	}
    
    public void newUploadItem(){
    	d.setContentView(R.layout.newupload);
    	d.setTitle("New File Upload");
		d.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		Button b = (Button) d.findViewById(R.id.button1);
		Button but = (Button) d.findViewById(R.id.browse);
		Spinner s = (Spinner)d.findViewById(R.id.category);
		ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, category_items);
		s.setAdapter(adapter);
		but.setOnClickListener(new View.OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			t = (TextView)d.findViewById(R.id.location);
    			filename = (EditText)d.findViewById(R.id.filename);
    			showFileChooser();
    		}
    	});
    	b.setOnClickListener(new View.OnClickListener() {
    		@Override
    		public void onClick(View v) {
    	    	String name = ((EditText)d.findViewById(R.id.filename)).getText().toString();
    	    	String comm = ((EditText)d.findViewById(R.id.comments)).getText().toString();
    	    	String loc = ((TextView)d.findViewById(R.id.location)).getText().toString();
        		Object sel = ((Spinner)d.findViewById(R.id.category)).getSelectedItem();
        		String cat = "";
        		if(sel != null)
        			cat = sel.toString();
        		if(path != ""){
    	    	File f = new File(path);
    	    	fileSize = f.length();
        		}
        		fileSize = 0;
    	    	size = Long.toString(fileSize);
    	    	Item i = new Item(name, (int) fileSize, loc, cat, comm, uploadList);
    	    	uploadList.add(i);
    	    	updateList();
    			d.dismiss();	
    		}
    	});
    	d.show();
    }
    
    public void updateList(){
    	list = (ListView)findViewById(R.id.uploadList);
        adapter = new UploadListView(this, uploadList);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new OnItemClickListener(){
        	@Override
      	    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        		final Dialog d = new Dialog(view.getContext());
        		String name = uploadList.get(position).getName();
            	String comm = uploadList.get(position).getComments();
            	String loc = uploadList.get(position).getPath();
            	String cat = uploadList.get(position).getCategory();
            	d.setContentView(R.layout.newupload);
            	d.setTitle("New File Upload");
        		d.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        		((EditText)d.findViewById(R.id.filename)).setText(name);
        		((EditText)d.findViewById(R.id.comments)).setText(comm);
        		((TextView)d.findViewById(R.id.location)).setText(loc);
        		ArrayAdapter myAdap = (ArrayAdapter)((Spinner)d.findViewById(R.id.category)).getAdapter(); //cast to an ArrayAdapter
        		int spinnerPosition = myAdap.getPosition(cat);
        		((Spinner)d.findViewById(R.id.category)).setSelection(spinnerPosition);
        		Button b = (Button) d.findViewById(R.id.button1);
        		Button but = (Button) d.findViewById(R.id.browse);
        		but.setOnClickListener(new View.OnClickListener() {
            		@Override
            		public void onClick(View v) {
            			t = (TextView)d.findViewById(R.id.location);
            			filename = (EditText)d.findViewById(R.id.filename);
            			showFileChooser();
            		}
            	});
            	b.setOnClickListener(new View.OnClickListener() {
            		@Override
            		public void onClick(View v) {
            	    	String name = ((EditText)d.findViewById(R.id.filename)).getText().toString();
            	    	String comm = ((EditText)d.findViewById(R.id.comments)).getText().toString();
            	    	String loc = ((TextView)d.findViewById(R.id.location)).getText().toString();
                		Object sel = ((Spinner)d.findViewById(R.id.category)).getSelectedItem();
                		String cat = "";
                		if(sel != null)
                			cat = sel.toString();
            	    	File f = new File(path);
            	    	long fileSize = f.length();
            	    	Item i = new Item(name, (int)fileSize, loc, cat, comm, uploadList);
            	    	uploadList.set(position, i);
            	    	updateList();
            			d.dismiss();
            		}
            	});
            	d.show();
            }
        });
    }
    
    public void setText(CharSequence text){
    	//((TextView)findViewById(R.id.uploadText)).setText(text);
    }
    
    public void setProgressBar(int ammount){
    	//((ProgressBar)findViewById(R.id.uploadProgressBar)).setProgress(ammount);
    }
    
    public void startProgress(){
				    	int mCount = 0;
				    	((RelativeLayout)findViewById(R.id.uploadingDialog)).setVisibility(0);
				    	mRun = true;
				    	while (mRun) {
				    		++mCount;
				    		SystemClock.sleep(100);
					    	CharSequence title = "Uploading: " + mCount%100 + "%";
					    	((ProgressBar)findViewById(R.id.uploadProgressBar)).setProgress(mCount%100);
					    	((TextView)findViewById(R.id.uploadText)).setText(title);
					    	if(mCount == 100){
					    		mRun = false;
					    		((RelativeLayout)findViewById(R.id.uploadingDialog)).setVisibility(4);
					    	}
				    	}
				    	
	}
    
    public void notif(View v){
        nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        CharSequence tickerText = "Moblie Upload";
        long when = System.currentTimeMillis();
        noti = new Notification(R.drawable.ic_launcher, tickerText, when);
        Context context = this.getApplicationContext();
        noti.flags |= Notification.FLAG_AUTO_CANCEL;
        Intent notiIntent = new Intent(context, Tab.class);
        PendingIntent pi = PendingIntent.getService(context, 0, notiIntent, 0);
        
        CharSequence title = "New Moblie Upload";
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
		 contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
		 contentView.setTextViewText(R.id.title, title);
		 contentView.setTextViewText(R.id.text, "Uploading: ");
		 contentView.setProgressBar(R.id.uploadProgress, 100, 0, false);
		 noti.contentView = contentView;
		 noti.contentIntent = pi;
        nm.notify(HELLO_ID, noti);
        //startProgress();
        new Thread(new Runnable() {
				    public void run() {
				    	int mCount = 0;
				    	mRun = true;
				    	while (mRun) {
				    		++mCount;
				    		SystemClock.sleep(100);
					    	CharSequence title = "Uploading: " + mCount%100 + "%";
					        noti.contentView.setTextViewText(R.id.text, title);
					        noti.contentView.setTextViewText(R.id.title, "New Mobile Upload");
					        noti.contentView.setProgressBar(R.id.uploadProgress, 100, mCount%100, false);
					    	nm.notify(HELLO_ID, noti);
					    	if(mCount == 100){
					    		mRun = false;
					    		nm.cancel(HELLO_ID);
					    	}
				    	}
				    	
				    }
				  }).start();
    }

    
    private static final int FILE_SELECT_CODE = 0;

    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
        intent.setType("*/*"); 
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(
                    Intent.createChooser(intent, "Select a File:"),
                    FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(this, "Please install a File Manager to use this action.", 
                    Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:      
            if (resultCode == RESULT_OK) {  
                Uri uri = data.getData();
                path = uri.getPath();
                String filename = "";
                for(int i = path.length()-1; i <= path.length()-1; i--){
                	if(path.charAt(i) == '/'){
                		filename = path.substring(i+1, path.length());
                		break;
                	}
                }
    			t.setText(path);
    			this.filename.setText(filename);
            }           
            break;
        }
    super.onActivityResult(requestCode, resultCode, data);
    }
    
	public void onBackPressed(){
		return;
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.settings:
                //method here
                return true;
            case R.id.info:
	 		     Intent intent = new Intent();
	 		     intent.setClass(this,Info.class);
	 		     startActivity(intent);
                return true;
            case R.id.signout:
	 		     Intent i = new Intent();
	 		     i.setClass(this,InfoPreserveActivity.class);
	 		     startActivity(i);
	 		     this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
